package com.song.service.Impl;

import com.song.dao.UserMapper;
import com.song.pojo.User;
import com.song.service.UserService;
import com.song.utils.PasswordUtil;
import com.song.utils.SystemConstant;
import com.song.utils.UUIDUtils;
import com.song.vo.UserVo;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * @author 宋超
 * HP - the login name of the current user.
 * 2020/12/27 - the current system date.
 * 16:35 - the current system time.
 */
@Transactional
@Service
public class UserServiceImpl implements UserService {

    @Resource
    private UserMapper userMapper;

    public int addUser(User user) {
        //自动生成盐值
        user.setSalt(UUIDUtils.randomUUID());//shiro安全验证框架

        user.setCreateDate(new Date());

        //密码加密
        user.setPassword(PasswordUtil.md5(user.getPassword(),user.getSalt(),
                SystemConstant.PASSWORD_COUNT));
        return userMapper.addUser(user);
    }

    //根据用户名查询用户信息
    public User findUserByName(String loginName) {
        return userMapper.findUserByName(loginName);
    }

    //用户登录
    public User login(String loginName, String password) {
        //获取登录用户信息
        User loginUser = userMapper.findUserByName(loginName);
        if (loginUser!=null){//判断对象是否为空
            //密码加密
            String newPassword = PasswordUtil.md5(password,loginUser.getSalt(),SystemConstant.PASSWORD_COUNT);
            //比较密码是否一致
            if(loginUser.getPassword().equals(newPassword)){
                return loginUser;
            }
        }
        return null;
    }

    //用户列表
    @Override
    public List<User> findUserList(UserVo userVo) {
        return userMapper.findUserList(userVo);
    }

    @Override
    public int updateUser(User user) {
        user.setCreateDate(new Date());
        return userMapper.updateUser(user);
    }

    @Override
    public int deleteById(int id) {
        //调用删除用户的方法
        return userMapper.deleteById(id);
    }

    @Override
    public User findUserById(Long id) {
        return userMapper.findById(id);
    }

    @Override
    public int updateUserInfo(User user) {
        return userMapper.updateUserInfo(user);
    }

}
